import 'dart:ui';
import 'package:liuxlcommon/lget/lget.dart';
import 'package:ladder_cash/app/com/view/my_app_bar.dart';
import 'package:ladder_cash/value/app_lstyle.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:ladder_cash/app/com/model/request_default_params_model.dart';
import 'package:ladder_cash/app/com/plugin/common_plugin.dart';
import 'package:ladder_cash/app/com/service/burial_point_service.dart';
import 'package:ladder_cash/app/key_mix.dart';
import 'package:ladder_cash/app/router_manage.dart';
import 'package:ladder_cash/generated/l10n.dart';
import 'package:ladder_cash/value/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/view/lxl_widget.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'my_web_logic.dart';

class MyWebPage extends StatefulWidget {
  String? url;

  Map? arguments;

  bool? loanAgree;

  MyWebPage({super.key, this.url, this.arguments, this.loanAgree});

  @override
  _MyWebPageState createState() => _MyWebPageState();
}

class _MyWebPageState extends State<MyWebPage> {
  final logic = Get.put(MyWebLogic());
  late final WebViewController _controller;
  double progress = 0;
  String? url;
  String title = S.current.appName;

  // GillyA(String url)页面跳转
  // SourceProducers()关闭当前webview
  // KristoferPremiered(String url, String params)带参数页面跳转
  // DescendantTime()回到首页，并关闭当前页
  // AlfieAnd()回到个人中心，并关闭当前页
  // SmallDisambiguation()跳转到登录页，并清空页面栈
  // MaddenFather(String phone)拨打电话号码（客户端补充"tel:"）
  // AndA() app store评分功能
  // OfSeries() 确认申请埋点调用方法


  static Map<String, String> jsFunName = {
    'pageTo': 'GillyA',
    'offAll': 'SourceProducers',
    'pageTo': 'KristoferPremiered',
    'offAllToHome': 'DescendantTime',
    'offAllToMine': 'AlfieAnd',
    'offAllToLogin': 'SmallDisambiguation',
    'dialNumber': 'MaddenFather',
    'score': 'AndA',
    'endApply': 'OfSeries',
    'startBank': 'a',
    'endBank': 'b',
  };

  List<String> jsactions = [
    '''
  DineroRaapidoAndroid = {
    ${jsFunName['pageTo']}:function (e){
      LocalDineroRaapidoAndroid.postMessage("pageTo|"+e)
    },
    ${jsFunName['offAll']}:function (){
      LocalDineroRaapidoAndroid.postMessage("offAll")
    },
    ${jsFunName['pageTo']}:function (url,params){
      LocalDineroRaapidoAndroid.postMessage("pageTo|"+url+"|"+params)
    },
    ${jsFunName['offAllToHome']}:function (){
      LocalDineroRaapidoAndroid.postMessage("offAllToHome")
    },
    ${jsFunName['offAllToMine']}:function (){
      LocalDineroRaapidoAndroid.postMessage("offAllToMine")
    },
    ${jsFunName['offAllToLogin']}:function (){
      LocalDineroRaapidoAndroid.postMessage("offAllToLogin")
    },
    ${jsFunName['dialNumber']}:function (e){
      LocalDineroRaapidoAndroid.postMessage("dialNumber|"+e)
    },
    ${jsFunName['score']}:function (){
      LocalDineroRaapidoAndroid.postMessage("score")
    },
    ${jsFunName['endApply']}:function (){
      LocalDineroRaapidoAndroid.postMessage("endApply")
    }
  }
  '''
  ];

  listenerJs(message) async {
    print("DineroRaapidoAndroid: " + message.message);
    List<String> data = (message.message as String).split('|');
    if (data[0] == 'pageTo') {
      RouterManage.to(data[1]);
    } else if (data[0] == 'offAll') {
      Get.back();
    } else if (data[0] == 'offAllToHome') {
      RouterManage.toTab(0);
    } else if (data[0] == 'offAllToMine') {
      RouterManage.toTab(2);
    } else if (data[0] == 'offAllToLogin') {
      // RouterManage.toTab(2);
    } else if (data[0] == 'dialNumber') {
      launch("tel:${data[1]}");
    } else if (data[0] == 'score') {
      CommonPlugin.goToRate;
    } else if (data[0] == 'endApply') {
      // String ache = message.message.substring(1, message.message.length - 1);
      await BurialPointService.start(BPoint.endApply, waitLocation: true);
      BurialPointService.end(BPoint.endApply);
    }
  }

  @override
  void initState() {
    super.initState();
    String params = "";
    RequestDefaultParamsModel? requestDefaultParamsModel =
        HttpRequest.requestDefaultParamsModel;
    params =
        '$params${'appVersion'.hx}=${requestDefaultParamsModel!.appVersion}';
    params =
        '$params&${'deviceName'.hx}=${requestDefaultParamsModel.deviceName}';
    params = '$params&${'deviceId'.hx}=${requestDefaultParamsModel.deviceId}';
    params =
        '$params&${'osVersion'.hx}=${requestDefaultParamsModel.deviceOsVersion}';
    params = '$params&${'sessionId'.hx}=${App.token}';
    params = '$params&${'gps_adid'.hx}=${requestDefaultParamsModel.adid}';
    params = '$params&${'isNeedPop'.hx}=${App.localeCode == "en" ? 1 : 2}';
    if (widget.url!.contains('?')) {
      widget.url = "${widget.url!}&$params";
    } else {
      widget.url = "${widget.url!}?$params";
    }

    if (widget.arguments != null) {
      for (String key in widget.arguments!.keys) {
        widget.url = "${widget.url!}&$key=${widget.arguments![key]}";
      }
    }

    // EasyLoading.showProgress(0, status: s.current.loading);

    var controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            print('WebView is loading (progress : $progress%)');
            this.progress = progress.toDouble() / 100;

            if (this.progress >= 1) {
              this.progress = 1;
              if (jsactions.isNotEmpty) _controller.runJavaScript(jsactions[0]);
              jsactions.clear();
              reGetTitle().then((t) {
                setState(() {
                  title = t;
                });
              });
            }
            logic.update(["progress"]);
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) async {
            var t = await reGetTitle();
            setState(() {
              title = t;
            });
          },
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            // if (checkURLScheme(request.url) != null) {
            //   launch(request.url);
            //   return NavigationDecision.prevent;
            // }
            return NavigationDecision.navigate;
          },
        ),
      )
      ..addJavaScriptChannel(jsFunName['pageTo']!,
          onMessageReceived: (message) {
        String tel = message.message.substring(1, message.message.length - 1);
        RouterManage.to(tel);
      })
      ..addJavaScriptChannel(jsFunName['offAll']!,
          onMessageReceived: (message) {
        Get.back();
      })
      ..addJavaScriptChannel(jsFunName['dialNumber']!,
          onMessageReceived: (message) {
        String tel = message.message.substring(1, message.message.length - 1);
        RouterManage.to(tel);
      })
      ..addJavaScriptChannel(jsFunName['offAllToHome']!,
          onMessageReceived: (message) {
        RouterManage.toTab(0);
      })
      ..addJavaScriptChannel(jsFunName['offAllToMine']!,
          onMessageReceived: (message) {
        RouterManage.toTab(2);
      })
      ..addJavaScriptChannel(jsFunName['offAllToLogin']!,
          onMessageReceived: (message) {
        App.logout();
      })
      // ..addJavaScriptChannel(jsFunName['score']!, onMessageReceived: (message) {
      //   String tel = message.message.substring(1, message.message.length - 1);
      //   launch("tel:${tel}");
      // })
      ..addJavaScriptChannel(jsFunName['startBank']!,
          onMessageReceived: (message) {
        BurialPointService.start(BPoint.bank);
      })
      ..addJavaScriptChannel(jsFunName['endBank']!,
          onMessageReceived: (message) {
        BurialPointService.end(BPoint.bank);
      })
      ..addJavaScriptChannel(jsFunName['score']!, onMessageReceived: (message) {
        CommonPlugin.goToRate;
      })
      ..addJavaScriptChannel(jsFunName['endApply']!,
          onMessageReceived: (JavaScriptMessage message) async {
        String? ache = "1";
        try {
          ache = message.message.substring(1, message.message.length - 1);
        } catch (e) {}
        await BurialPointService.start(BPoint.endApply);
        BurialPointService.end(BPoint.endApply, ache: ache);
      })
      ..addJavaScriptChannel("LocalDineroRaapidoAndroid",
          onMessageReceived: (message) {
        listenerJs(message);
      })
      ..loadRequest(Uri.parse(widget.url ?? ''));
    _controller = controller;
  }

  // String? checkURLScheme(String url) {
  //   List<String> schemes = [
  //     'mobikwik://',
  //     'PhonePe://',
  //     'paytm://',
  //     'paytmmp://',
  //     'gpay://',
  //     'upi://',
  //     'weixin://'
  //   ];
  //   for (String scheme in schemes) {
  //     if (url.toUpperCase().startsWith(scheme.toUpperCase())) {
  //       return url;
  //     }
  //   }
  //   return null;
  // }

  int count = -1;

  ///如果获取的是错误的titile ，可以递归执行 这个方法。
  Future<String> reGetTitle({count = -1}) async {
    if (this.count >= 5) {
      this.count = -1;
      return title;
    }
    if (this.count == count) {
      title = await _controller.getTitle() ?? "";
      if (title.contains(App.token ?? "")) {
        this.count++;
        await Future.delayed(const Duration(milliseconds: 100));
        title = await reGetTitle(count: this.count);
      }
    }
    return title;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.bgColor,
      appBar: MyAppBar(
        StringUtils.defaultValue(title, S.current.appName),
        backClick: () async {
          if (await _controller.canGoBack()) {
            _controller.goBack();
          } else
            Get.back();
        },
      ),
      body: WillPopScope(
        onWillPop: () async {
          if (widget.url != null) return true;
          if (url != null) {
            if (url!.contains("/")) {
              _controller.goBack();
            } else {
              SystemNavigator.pop();
            }
          }
          return false;
        },
        child: Column(
          children: [
            LExpand(
              child: Stack(
                children: [
                  WebViewWidget(
                    controller: _controller,
                  ),
                  GetBuilder<MyWebLogic>(
                      id: 'progress',
                      builder: (logic) => progress >= 1
                          ? const SizedBox()
                          : LinearProgressIndicator(
                              value: progress,
                              backgroundColor: Colors.grey[300],
                              valueColor: AlwaysStoppedAnimation<Color>(
                                  AppColors.primaryColor),
                            ))
                ],
              ),
            ),
            if (widget.loanAgree == true)
              LText(App.localeEn ? 'Apply' : 'Aplicar')
                  .style(rzBtnSty)
                  .margin(top: 10.w, bottom: LGet.bottomPadding(context) + 10.w)
                  .onTapL(() {
                Get.back(result: true);
              })
          ],
        ),
      ),
      // floatingActionButton:FloatingActionButton(
      //     onPressed: () =>
      //         _controller.runJavaScript("DineroRaapidoAndroid.pink()"),
      //     child: const Text("测试")),
    );
  }

  // defiance(String url)页面跳转
  // overborne()关闭当前webview
  // braved(String url, String params)带参数页面跳转
  // itself()回到首页，并关闭当前页
  // pretended()回到个人中心，并关闭当前页
  // seduction()跳转到登录页，并清空页面栈
  // crime(String phone)拨打电话号码（客户端补充"tel:"）
  // proved() app store评分功能
  // conceive() 确认申请埋点调用方法

  @override
  void dispose() {
    Get.delete<MyWebLogic>();
    super.dispose();
  }
}
